<?php

namespace App\Admin\Renderable;

use App\Support\Data;
use Dcat\Admin\Admin;
use Dcat\Admin\Grid;
use Dcat\Admin\Grid\LazyRenderable;
use Dcat\Admin\Models\Administrator;
use Illuminate\Database\Eloquent\Builder;

class UserTable extends LazyRenderable
{
    public function grid(): Grid
    {
        // 获取外部传递的参数
        $company_id = $this->company_id;

        return Grid::make(Administrator::with(['roles']), function (Grid $grid) use ($company_id) {
            // 如果有搜索的时候，只搜索本公司内的
            $admin = Admin::user();
            if ((!empty($grid->filter()->input('username'))) || (!empty($grid->filter()->input('name'))) || (!empty($grid->filter()->input('region')))) {
                $grid->model()->where('company_id', $company_id);
                if (Admin::user()->isRole('regional-supervisor')) {
                    $grid->model()->where('region', $admin['region']);
                }
            } else {
                if (!Admin::user()->isAdministrator()) {
                    $grid->model()->where('company_id', $company_id);
                    if (Admin::user()->isRole('regional-supervisor')) {
                        $grid->model()->where('region', $admin['region']);
                    }
                } else {
                    $grid->model()->where('company_id',  $company_id)->orWhere(function (Builder $query) {
                        $query->where('is_external', 0)->where('company_id', null);
                    });
                }
            }

            $grid->column('id');
            $grid->column('username');
            $grid->column('name');
            $grid->column('region', '区域')->display(function ($id) {
                $arr = Data::getRegion();
                return isset($arr[$id]) ? $arr[$id] : ' - ';
            });
            $grid->column('roles.0.name', '角色');
            // $grid->column('created_at');
            // $grid->column('updated_at');

            // $grid->quickSearch(['id', 'username', 'name']);

            $grid->model()->orderBy('created_at', 'desc');
            $grid->paginate(10);
            $grid->disableActions();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->like('username')->width(4);
                $filter->like('name')->width(4);
                $filter->equal('region', '区域')->select(Data::getRegion());
            });
        });
    }
}
